package com.xjj.mall.service.impl;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.xjj.framework.web.support.XJJParameter;
import com.xjj.mall.common.exception.XmallException;
import com.xjj.mall.common.jedis.JedisClient;
import com.xjj.mall.common.pojo.DataTablesResult;
import com.xjj.mall.dao.ItemDao;
import com.xjj.mall.dao.ItemDescDao;
import com.xjj.mall.dao.PanelContentDao;
import com.xjj.mall.dao.PanelDao;
import com.xjj.mall.entity.ItemDescEntity;
import com.xjj.mall.entity.ItemEntity;
import com.xjj.mall.entity.PanelContentEntity;
import com.xjj.mall.entity.PanelEntity;
import com.xjj.mall.pojo.AllGoodsResult;
import com.xjj.mall.pojo.Product;
import com.xjj.mall.pojo.ProductDet;
import com.xjj.mall.service.ContentService;
import com.xjj.mall.util.DtoUtil;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author zhanghejie
 */
@Service
public class ContentServiceImpl implements ContentService {

    private final static Logger log= LoggerFactory.getLogger(PanelServiceImpl.class);

    @Autowired
    private PanelDao panelDao;
    @Autowired
    private PanelContentDao panelContentDao;
    @Autowired
    private ItemDao itemDao;
    @Autowired
    private ItemDescDao itemDescDao;
    @Autowired
    private JedisClient jedisClient;

    @Value("${PRODUCT_HOME}")
    private String PRODUCT_HOME;

    @Value("${PRODUCT_ITEM}")
    private String PRODUCT_ITEM;

    @Value("${RECOMEED_PANEL_ID}")
    private Long RECOMEED_PANEL_ID;

    @Value("${THANK_PANEL_ID}")
    private Long THANK_PANEL_ID;

    @Value("${RECOMEED_PANEL}")
    private String RECOMEED_PANEL;

    @Value("${THANK_PANEL}")
    private String THANK_PANEL;

    @Value("${ITEM_EXPIRE}")
    private int ITEM_EXPIRE;

    @Value("${HEADER_PANEL_ID}")
    private Long HEADER_PANEL_ID;

    @Value("${HEADER_PANEL}")
    private String HEADER_PANEL;

    @Override
    public int addPanelContent(PanelContentEntity tbPanelContent) {

        tbPanelContent.setCreated(new Date());
        tbPanelContent.setUpdated(new Date());
        panelContentDao.save(tbPanelContent);
        //同步导航栏缓存
        if(tbPanelContent.getPanelId()==HEADER_PANEL_ID){
            updateNavListRedis();
        }
        //同步缓存
        deleteHomeRedis();
        return 1;
    }

    @Override
    public DataTablesResult getPanelContentListByPanelId(Long panelId) {

        DataTablesResult result=new DataTablesResult();
//        List<PanelContentEntity> list=new ArrayList<>();
//
//        TbPanelContentExample example=new TbPanelContentExample();
//        TbPanelContentExample.Criteria criteria=example.createCriteria();
//        //条件查询
//        criteria.andPanelIdEqualTo(panelId);
//        list=tbPanelContentMapper.selectByExample(example);
        
        List<PanelContentEntity> list = panelContentDao.findListByColumn("panel_id", panelId);
        for(PanelContentEntity content:list){
            if(content.getProductId()!=null){
                ItemEntity tbItem=itemDao.getById(content.getProductId());
                content.setProductName(tbItem.getTitle());
                content.setSalePrice(tbItem.getPrice());
                content.setSubTitle(tbItem.getSellPoint());
            }
        }

        result.setData(list);
        return result;
    }

    @Override
    public int deletePanelContent(Long id) {

    	panelContentDao.delete(id);
        //同步导航栏缓存
        if(id==HEADER_PANEL_ID){
            updateNavListRedis();
        }
        //同步缓存
        deleteHomeRedis();
        return 1;
    }

    @Override
    public int updateContent(PanelContentEntity tbPanelContent) {

    	PanelContentEntity old=getTbPanelContentById(tbPanelContent.getId());
        if(StringUtils.isBlank(tbPanelContent.getPicUrl())){
            tbPanelContent.setPicUrl(old.getPicUrl());
        }
        if(StringUtils.isBlank(tbPanelContent.getPicUrl2())){
            tbPanelContent.setPicUrl2(old.getPicUrl2());
        }
        if(StringUtils.isBlank(tbPanelContent.getPicUrl3())){
            tbPanelContent.setPicUrl3(old.getPicUrl3());
        }
        tbPanelContent.setCreated(old.getCreated());
        tbPanelContent.setUpdated(new Date());
        panelContentDao.update(tbPanelContent);
        //同步导航栏缓存
        if(tbPanelContent.getPanelId()==HEADER_PANEL_ID){
            updateNavListRedis();
        }
        //同步缓存
        deleteHomeRedis();
        return 1;
    }

    @Override
    public PanelContentEntity getTbPanelContentById(Long id) {

        PanelContentEntity tbPanelContent=panelContentDao.getById(id);
        if(tbPanelContent==null){
            throw new XmallException("通过id获取板块内容失败");
        }
        return tbPanelContent;
    }

    @Override
    public List<PanelEntity> getHome() {

        List<PanelEntity> list=null;

        //查询缓存
        try{
            //有缓存则读取
            String json=jedisClient.get(PRODUCT_HOME);
            if(json!=null){
                list = new Gson().fromJson(json, new TypeToken<List<PanelEntity>>(){}.getType());
                log.info("读取了首页缓存");
                return list;
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        //没有缓存
        XJJParameter param = new XJJParameter();
        param.addQuery("query.position@eq@i",0);
        param.addQuery("query.status@eq@i",1);
        param.addOrderByAsc("sortOrder");
        list = panelDao.findList(param.getQueryMap());
        
        for(PanelEntity tbPanel:list){
//            TbPanelContentExample exampleContent=new TbPanelContentExample();
//            exampleContent.setOrderByClause("sort_order");
//            TbPanelContentExample.Criteria criteriaContent=exampleContent.createCriteria();
//            //条件查询
//            criteriaContent.andPanelIdEqualTo(tbPanel.getId());
//            List<TbPanelContent> contentList=tbPanelContentMapper.selectByExample(exampleContent);
            
        	param.clear();
        	param.addQuery("query.panelId@eq@l",tbPanel.getId());
        	 param.addOrderByAsc("sortOrder");
        	List<PanelContentEntity> contentList = panelContentDao.findList(param.getQueryMap());
        	 
        	for(PanelContentEntity content:contentList){
                if(content.getProductId()!=null){
                    ItemEntity tbItem=itemDao.getById(content.getProductId());
                    content.setProductName(tbItem.getTitle());
                    content.setSalePrice(tbItem.getPrice());
                    content.setSubTitle(tbItem.getSellPoint());
                    content.setProductImageBig(content.getPicUrl());
                }
            }

            tbPanel.setPanelContents(contentList);
        }

        //把结果添加至缓存
        try{
            jedisClient.set(PRODUCT_HOME, new Gson().toJson(list));
            log.info("添加了首页缓存");
        }catch (Exception e){
            e.printStackTrace();
        }
        return list;
    }

    @Override
    public List<PanelEntity> getRecommendGoods() {


        List<PanelEntity> list = new ArrayList<>();
        //查询缓存
        try{
            //有缓存则读取
            String json=jedisClient.get(RECOMEED_PANEL);
            if(json!=null){
                list = new Gson().fromJson(json, new TypeToken<List<PanelEntity>>(){}.getType());
                log.info("读取了推荐板块缓存");
                return list;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        list = getTbPanelAndContentsById(RECOMEED_PANEL_ID);
        //把结果添加至缓存
        try{
            jedisClient.set(RECOMEED_PANEL, new Gson().toJson(list));
            log.info("添加了推荐板块缓存");
        }catch (Exception e){
            e.printStackTrace();
        }
        return list;
    }

    @Override
    public List<PanelEntity> getThankGoods() {

        List<PanelEntity> list = new ArrayList<>();
        //查询缓存
        try{
            //有缓存则读取
            String json=jedisClient.get(THANK_PANEL);
            if(json!=null){
                list = new Gson().fromJson(json, new TypeToken<List<PanelEntity>>(){}.getType());
                log.info("读取了捐赠板块缓存");
                return list;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        list = getTbPanelAndContentsById(THANK_PANEL_ID);
        //把结果添加至缓存
        try{
            jedisClient.set(THANK_PANEL, new Gson().toJson(list));
            log.info("添加了捐赠板块缓存");
        }catch (Exception e){
            e.printStackTrace();
        }
        return list;
    }

    private List<PanelEntity> getTbPanelAndContentsById(Long panelId){

  //  	List<PanelEntity> list=new ArrayList<>();
//        TbPanelExample example=new TbPanelExample();
//        TbPanelExample.Criteria criteria=example.createCriteria();
//        //条件查询
//        criteria.andIdEqualTo(panelId);
//        criteria.andStatusEqualTo(1);
//        list=tbPanelMapper.selectByExample(example);
        
        XJJParameter param = new XJJParameter();
        param.addQuery("query.id@eq@l",panelId);
        param.addQuery("query.status@eq@i",1);
        List<PanelEntity> list = panelDao.findList(param.getQueryMap());
        
        
        for(PanelEntity tbPanel:list){
//            PanelContentExample exampleContent=new TbPanelContentExample();
//            exampleContent.setOrderByClause("sort_order");
//            TbPanelContentExample.Criteria criteriaContent=exampleContent.createCriteria();
//            //条件查询
//            criteriaContent.andPanelIdEqualTo(tbPanel.getId());
//            List<TbPanelContent> contentList=tbPanelContentMapper.selectByExample(exampleContent);
        	
        	param.clear();
        	param.addQuery("query.panelId@eq@l",tbPanel.getId());
        	param.addOrderByAsc("sortOrder");
        	List<PanelContentEntity> contentList = panelContentDao.findList(param.getQueryMap());
        	
        	
        	
            for(PanelContentEntity content:contentList){
                if(content.getProductId()!=null){
                    ItemEntity tbItem=itemDao.getById(content.getProductId());
                    content.setProductName(tbItem.getTitle());
                    content.setSalePrice(tbItem.getPrice());
                    content.setSubTitle(tbItem.getSellPoint());
                }
            }

            tbPanel.setPanelContents(contentList);
        }
        return list;
    }

    @Override
    public ProductDet getProductDet(Long id) {

        //查询缓存
        try{
            //有缓存则读取
            String json=jedisClient.get(PRODUCT_ITEM+":"+id);
            if(json!=null){
                ProductDet productDet= new Gson().fromJson(json,ProductDet.class);
                log.info("读取了商品"+id+"详情缓存");
                //重置商品缓存时间
                jedisClient.expire(PRODUCT_ITEM+":"+id,ITEM_EXPIRE);
                return productDet;
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        ItemEntity tbItem=itemDao.getById(id);
        ProductDet productDet=new ProductDet();
        productDet.setProductId(id);
        productDet.setProductName(tbItem.getTitle());
        productDet.setSubTitle(tbItem.getSellPoint());
        if(tbItem.getLimitNum()!=null&&!tbItem.getLimitNum().toString().isEmpty()){
            productDet.setLimitNum(Long.valueOf(tbItem.getLimitNum()));
        }else{
            productDet.setLimitNum(Long.valueOf(tbItem.getNum()));
        }
        productDet.setSalePrice(tbItem.getPrice());
        ItemDescEntity tbItemDesc=itemDescDao.getByColumn("item_id",id);
        productDet.setDetail(tbItemDesc.getItemDesc());

        if(tbItem.getImage()!=null&&!tbItem.getImage().isEmpty()){
            String images[]=tbItem.getImage().split(",");
            productDet.setProductImageBig(images[0]);
            List list=new ArrayList();
            for(int i=0;i<images.length;i++){
                list.add(images[i]);
            }
            productDet.setProductImageSmall(list);
        }
        //无缓存 把结果添加至缓存
        try{
            jedisClient.set(PRODUCT_ITEM+":"+id,new Gson().toJson(productDet));
            //设置过期时间
            jedisClient.expire(PRODUCT_ITEM+":"+id,ITEM_EXPIRE);
            log.info("添加了商品"+id+"详情缓存");
        }catch (Exception e){
            e.printStackTrace();
        }
        return productDet;
    }

    @Override
    public AllGoodsResult getAllProduct(int page, int size, String sort, Long cid, Long priceGt, Long priceLte) {

//        AllGoodsResult allGoodsResult=new AllGoodsResult();
//        List<Product> list=new ArrayList<>();
//        //分页执行查询返回结果
//        if(page<=0) {
//            page = 1;
//        }
//        PageHelper.startPage(page,size);
//
//        //判断条件
//        String orderCol="created";
//        String orderDir="desc";
//        if(sort.equals("1")){
//            orderCol="price";
//            orderDir="asc";
//        }else if(sort.equals("-1")){
//            orderCol="price";
//            orderDir="desc";
//        }else{
//            orderCol="created";
//            orderDir="desc";
//        }
    	
//    	<select id="selectItemFront" resultMap="BaseResultMap">
//        SELECT * FROM tb_item
//        WHERE status = 1
//        <if test="priceGt != null and priceGt >= 0 and priceLte != null and priceLte >= 0">
//          AND price BETWEEN #{priceGt} AND #{priceLte}
//        </if>
//        <if test="cid != null">
//          AND cid = #{cid}
//        </if>
//        ORDER BY
//        ${orderCol}
//        ${orderDir}
//      </select>
    	
    	
    	XJJParameter param = new XJJParameter();
        param.addQuery("query.status@eq@i",1);
        
        if(null!=cid)
        {
        	param.addQuery("query.cid@eq@l",cid);
        }
        
        if(null!=priceGt && priceGt >= 0)
        {
        	param.addQuery("query.price@ge@l",priceGt);
        }
        
        if(null!=priceLte && priceLte >= 0)
        {
        	param.addQuery("query.price@le@l",priceLte);
        }
        
        

        List<ItemEntity> tbItemList = itemDao.findListLimit(param.getQueryMap(), (page-1)*size, size);
        
        int totalCount = itemDao.getCount(param.getQueryMap());
        
        //PageInfo<TbItem> pageInfo=new PageInfo<>(tbItemList);
        List<Product> list=new ArrayList<>();
        for(ItemEntity tbItem:tbItemList){
            Product product= DtoUtil.TbItem2Product(tbItem);
            list.add(product);
        }

        AllGoodsResult allGoodsResult=new AllGoodsResult();
        allGoodsResult.setData(list);
        allGoodsResult.setTotal(totalCount);

        return allGoodsResult;
    }

    @Override
    public String getIndexRedis() {

        try{
            String json=jedisClient.get(PRODUCT_HOME);
            return json;
        }catch (Exception e){
            log.error(e.toString());
        }
        return "";
    }

    @Override
    public int updateIndexRedis() {

        deleteHomeRedis();
        return 1;
    }

    @Override
    public String getRecommendRedis() {

//        try{
//            String json=jedisClient.get(RECOMEED_PANEL);
//            return json;
//        }catch (Exception e){
//            log.error(e.toString());
//        }
        return "";
    }

    @Override
    public int updateRecommendRedis() {

        try {
            jedisClient.del(RECOMEED_PANEL);
        }catch (Exception e){
            e.printStackTrace();
        }
        return 1;
    }

    @Override
    public String getThankRedis() {

        try{
            String json=jedisClient.get(THANK_PANEL);
            return json;
        }catch (Exception e){
            log.error(e.toString());
        }
        return "";
    }

    @Override
    public int updateThankRedis() {
//
        try {
            jedisClient.del(THANK_PANEL);
        }catch (Exception e){
            e.printStackTrace();
        }
        return 1;
    }

    public void updateNavListRedis() {

        try {
            jedisClient.del(HEADER_PANEL);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public List<PanelContentEntity> getNavList() {

        List<PanelContentEntity> list = new ArrayList<>();
        //查询缓存
        try{
            //有缓存则读取
            String json=jedisClient.get(HEADER_PANEL);
            if(json!=null){
                list = new Gson().fromJson(json, new TypeToken<List<PanelContentEntity>>(){}.getType());
                log.info("读取了导航栏缓存");
                return list;
            }
        }catch (Exception e){
            e.printStackTrace();
        }

//        TbPanelContentExample exampleContent=new TbPanelContentExample();
//        exampleContent.setOrderByClause("sort_order");
//        TbPanelContentExample.Criteria criteriaContent=exampleContent.createCriteria();
//        //条件查询
//        criteriaContent.andPanelIdEqualTo(HEADER_PANEL_ID);
//        list=tbPanelContentMapper.selectByExample(exampleContent);
        
        XJJParameter param = new XJJParameter();
        param.addQuery("query.panelId@eq@l",HEADER_PANEL_ID);
        param.addOrderByAsc("sortOrder");
        list = panelContentDao.findList(param.getQueryMap());
        
        //把结果添加至缓存
        try{
            jedisClient.set(HEADER_PANEL, new Gson().toJson(list));
            log.info("添加了导航栏缓存");
        }catch (Exception e){
            e.printStackTrace();
        }

        return list;
    }

    /**
     * 同步首页缓存
     */
    public void deleteHomeRedis(){
        try {
            jedisClient.del(PRODUCT_HOME);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
